<?php

declare (strict_types=1);


namespace app\api\controller;

use app\common\model\User;
use app\common\model\VerificationCode;
use app\common\tool\Result;
use think\Response;
use think\exception\ValidateException;
use addons\WeChatMini\facade\WeChatMini;
use addons\WeChat\facade\WeChat;

/**
 * 登录
 */
class Login extends Base
{
    /**
     * 微信小程序登录
     */
    public function  miniAppletLogin()
    {
        try {
            $param = $this->request->post();
            if(!isset($param['code']) || empty($param['code'])){
                return Result::fail('请重新获取授权！');
            }
            $phone = WeChatMini::session($param['code']);
            if (!empty($phone) && isset($phone['openid'])) {
                $param['openid'] = $phone['openid'];
                return Result::fastReturn(User::_miniAppletSave($param));
            } else {
                return Result::fail('请重新获取授权！');
            }
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    
    public function weiXinOauth()
    {

        try {
            $code = $this->request->param('code');
            if (!empty($code)) {
                $res = WeChat::getOauthAccessToken($code);
                if (isset($res['openid'])) {
                    return Result::success('获取成功！', $res);
                } else {
                    return Result::fail('服务器错误！');
                }
            } else {
                return Result::fail('请重新获取授权！');
            }
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

}